<?php
/**
 * 常用的函数
 */
!defined('IN_FRAME') && die('404 Page');
class Helper {
    
    /**
     * 关闭窗口
     * $strExtJs = 'window.opener.$("#id_seo_k").val("aabbcc");';
     */
    public static function jsCloseWindow($strMsg = '', $strExtJs = '') {
        $strAlert = !empty($strMsg) ? 'alert("' . addslashes($strMsg) . '");' : '';
        $strJs = <<<JS
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <script type="text/javascript">
            {$strAlert}
            {$strExtJs}
            window.close();
        </script>
    </body>
</html>
JS;
        define('DO_NOT_CACHE_ME', 'yes');
        die($strJs);
    }
    
    /**
     * 跳转
     * --- 若无特别需求,请勿修改此函数,谢谢 ---
     * @param $strUrl 要跳转到的链接
     * @param $strMsg 跳转前的提示信息
     */
    public static function jsLoadTo($strUrl = '/', $strMsg = '') {
        if ('/' == $strUrl) {
            $strUrl = HTTP_URL;
        }
        $strAlert = !empty($strMsg) ? 'alert("' . addslashes($strMsg) . '");' : '';
        $strJs = <<<JS
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <script type="text/javascript">
            {$strAlert}
            window.top.location.href = "{$strUrl}";
        </script>
    </body>
</html>
JS;
        define('DO_NOT_CACHE_ME', 'yes');
        die($strJs);
    }
    
    /**
     * 加载模型
     * --- 若无特别需求,请勿修改此函数,谢谢 ---
     * @param $strName 模型名称
     * @param $blnInit 是否立即单态实例(是否需要,有待证实)
     */
    public static function loadModel($strName, $blnInit = true) {
        static $arrSingleModels = array();
        $objRe = null;
        if (!empty($strName)) {
            $strKey = md5($strName);
            if (isset($arrSingleModels[$strKey])) {
                $objRe = $arrSingleModels[$strKey];
            } else {
                $strClass = 'm_' . $strName;
                if (class_exists($strClass, true)) {
                    if ($blnInit) {
                        $objRe = new $strClass;
                        $arrSingleModels[$strKey] = $objRe;
                    } else {
                        $objRe = true;
                    }
                }
            }
        }
        return $objRe;
    }
    
    /**
     * 取随机字符串
     */
    public static function getRandStr($how = 4, $only = '') {
        srand((double)microtime() * 1000000); // 初始化随机数种子
        $alpha = "abcdefghjkmnpqrstuvwxyABCDEFGHJKLMNPQRSTUVWXY"; // 验证码内容1:字母
        $number = "3456789"; // 验证码内容2:数字
        if ('number' == $only) {
            $alpha = $number;
        } elseif ('alpha' == $only) {
            $number = $alpha;
        }
        $randcode = '';
        $i = 0;
        while ($i < $how) {
            $i ++;
            $str = mt_rand(0, 1) ? $alpha : $number;
            $randcode .= substr($str, mt_rand(0, (strlen($str) - 1)), 1); // 逐位加入验证码字符串
        }
        return $randcode;
    }
    
    /**
     * 是Ajax请求吗?
     */
    public static function isAjaxRequest() {
        return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest');
    }
    
    /**
     * 生成路径文件
     */
    public static function getUploadFilePath($strExt = null) {
        $strPath = UPLOADS_PATH . '/' . date('y');
        !file_exists($strPath) && mkdir($strPath, 0777) && copy(UPLOADS_PATH . '/index.html', $strPath . '/index.html');
        $strPath .= '/' . date('m');
        !file_exists($strPath) && mkdir($strPath, 0777) && copy(UPLOADS_PATH . '/index.html', $strPath . '/index.html');
        $strPath .= '/' . date('d');
        !file_exists($strPath) && mkdir($strPath, 0777) && copy(UPLOADS_PATH . '/index.html', $strPath . '/index.html');
        return array(
            'path' => $strPath,
            'name' => !is_null($strExt) ? (date('His') . self::getRandStr()) . $strExt : ''
        );
    }
    
    /**
     * 返回不同尺寸图片的URL
     */
    public static function getThumbUrl($path, $w, $h) {
        $strRe = '';
        if (file_exists(ROOT_PATH . $path)) {
            // TODO
        }
        return $strRe;
    }
    
    public static function addWaterMaker($strPath) {
        $objThumb = PhpThumbFactory::create($strPath);
        $objThumb->createWatermark(ROOT_PATH . '/uploads/watermaker.png', 10, 10);
        $objThumb->save($strPath);
    }
    
    /**
     * 处理单个上传的文件
     */
    public static function saveUploadedFile($strField = 'img_file', $arrAllowed = array('.jpg', '.jpeg', '.gif', '.png'), $arrNotAllowed = array('.php', '.exe', '.html'), $intMaxSize = 10485760) {
        $arrRe = array('ok' => false, 'path' => '', 'msg' => '');
        if ($_FILES && $_FILES[$strField] && $_FILES[$strField]['name']) {
            if ($_FILES[$strField]['size'] > $intMaxSize) {
                $arrRe['msg'] = 'ERR_1'; // 文件过大
            } else {
                $strExt = substr($_FILES[$strField]['name'], strrpos($_FILES[$strField]['name'], '.'));
                $strExt = strtolower($strExt);
                if (is_array($arrAllowed) && !in_array($strExt, $arrAllowed)) {
                    $arrRe['msg'] = 'ERR_2'; // 不允许此类型文件
                } elseif (is_array($arrNotAllowed) && in_array($strExt, $arrNotAllowed)) {
                    $arrRe['msg'] = 'ERR_2'; // 不允许此类型文件
                } else {
                    $arrTemp = self::getUploadFilePath($strExt);
                    $strPath = $arrTemp['path'];
                    $strFileName = $arrTemp['name'];
                    if (move_uploaded_file($_FILES[$strField]['tmp_name'], $strPath . '/' . $strFileName)) {
                        self::addWaterMaker($strPath . '/' . $strFileName);
                        $arrRe['ok'] = true;
                        $arrRe['path'] = str_replace(ROOT_PATH, '', $strPath) . '/' . $strFileName;
                    } else {
                        $arrRe['msg'] = 'ERR_3'; // 上传最终失败
                    }
                }
            }
        } else {
            $arrRe['msg'] = 'ERR_0'; // 没有文件
        }
        return $arrRe;
    }
    
    /**
     * 检查用户输入是否有以下字符
     */
    public static function hasBadword($str) {
        $bln = false;
        $arr = array("\\", '&', ' ', "'", '"', '/', '*', ',', '<', '>', "\r", "\t", "\n", "#");
        foreach($arr as $s) {
            if (strpos($str, $s) !== false) {
                $bln = true;
                break;
            }
        }
        return $bln;
    }
    
    /**
     * 是否Eamil字符串
     */
    public static function isEmail($str) {
        return filter_var($str, FILTER_VALIDATE_EMAIL);
    }
    
    /**
     * 分词
     */
    public static function fenCi($str, $blnReStr = true) {
        $sp = new SplitWord();
        $sp->SetSource($str);
        $sp->StartAnalysis(true);
        $str = preg_replace("/#p#|#e#/", '', $sp->GetFinallyIndex());
        if (is_array($str) && count($str) > 0) {
            $str = array_keys($str);
            $blnReStr && $str = implode(' ', $str);
        } else {
            $str = '';
        }
        return $str;
    }
    
    /**
     * 获得索引
     */
    public static function genIndexStr($str, $code = 'utf8') {
        $strRe = '';
        $str = strip_tags($str);
        $str = preg_replace("/[[:punct:]]/", ' ', $str);
        $intLen = mb_strlen($str, $code);
        if ($intLen > 0) {
            $intTemp = 0;
            $arrTemp = array();
            while ($intTemp < $intLen) {
                $strTemp = mb_substr($str, $intTemp, 1, $code);
                preg_match('/^[0-9a-zA-Z\s]$/', $strTemp, $arrTemp);
                $strRe .=  ((count($arrTemp) > 0) ? $strTemp : str_replace('%', '', urlencode($strTemp)));
                $intTemp ++;
            }
        }
        return trim($strRe);
    }
    
    /**
     * 字符截取 支持UTF8
     */
    public static function strCut($string, $length, $dot = '...') {
        $strlen = strlen($string);
        if ($strlen <= $length) {
            return $string;
        }
        $string = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵', ' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
        $strcut = '';
        $length = intval($length - strlen($dot) - $length/3);
        $n = $tn = $noc = 0;
        $strlen = strlen($string);
        while ($n < $strlen) {
            $t = ord($string[$n]);
            if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                $tn = 1; $n++; $noc++;
            } elseif (194 <= $t && $t <= 223) {
                $tn = 2; $n += 2; $noc += 2;
            } elseif (224 <= $t && $t <= 239) {
                $tn = 3; $n += 3; $noc += 2;
            } elseif (240 <= $t && $t <= 247) {
                $tn = 4; $n += 4; $noc += 2;
            } elseif (248 <= $t && $t <= 251) {
                $tn = 5; $n += 5; $noc += 2;
            } elseif ($t == 252 || $t == 253) {
                $tn = 6; $n += 6; $noc += 2;
            } else {
                $n++;
            }
            if ($noc >= $length) {
                break;
            }
        }
        if ($noc > $length) {
            $n -= $tn;
        }
        $strcut = substr($string, 0, $n);
        $strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
        return $strcut.$dot;
    }
    
    
    /**
     * 取数据的维度
     */
    public static function getArrDeep($arr) {
        $re = 0;
        if (is_array($arr)) {
            $re = 1;
            $arrTemp = array();
            foreach ($arr as $a) {
                is_array($a) && array_push($arrTemp, Helper::getArrDeep($a));
            }
            count($arrTemp) > 0 && $re += max($arrTemp);
        }
        return $re;
    }
    
}